﻿using System;
using System.Text;
using System.IO;
using System.Web;
using SystemX.Infrastructure;
using System.Net;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Web.Security;

namespace SystemX.Web
{
    public static partial class Utils
    {
        /// <summary>
        /// Get a view's relative path.
        /// </summary>
        /// <param name="folderName">folder Name</param>
        /// <param name="viewID">view's id</param>
        /// <returns></returns>
        public static string ViewPath(string folderName, string viewID)
        {
            StringBuilder retVal = new StringBuilder();
            retVal.AppendFormat("~/Views/{0}/{1}.ascx", folderName, viewID);
            return retVal.ToString();
        }
        #region upload methods
        //swfupload control's cookie bug fix
        public static void SWFUploadBugFix()
        {
            /* Fix for the Flash Player Cookie bug in Non-IE browsers.
             * Since Flash Player always sends the IE cookies even in FireFox
             * we have to bypass the cookies by sending the values as part of the POST or GET
             * and overwrite the cookies with the passed in values.
             * 
             * The theory is that at this point (BeginRequest) the cookies have not been read by
             * the Session and Authentication logic and if we update the cookies here we'll get our
             * Session and Authentication restored correctly
             */

            try
            {
                string session_param_name = "ASPSESSID";//passed by SWFUpload url
                string session_cookie_name = "ASP.NET_SESSIONID";

                if (HttpContext.Current.Request.Form[session_param_name] != null)
                {
                    Utils.UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
                {
                    Utils.UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
                }
            }
            catch (Exception)
            {
                HttpContext.Current.Response.StatusCode = 500;
                HttpContext.Current.Response.Write("Error Initializing Session");
            }

            try
            {
                string auth_param_name = "AUTHID";//passed by SWFUpload url
                string auth_cookie_name = FormsAuthentication.FormsCookieName;

                if (HttpContext.Current.Request.Form[auth_param_name] != null)
                {
                    Utils.UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
                }
                else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
                {
                    Utils.UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
                }

            }
            catch (Exception)
            {
                HttpContext.Current.Response.StatusCode = 500;
                HttpContext.Current.Response.Write("Error Initializing Forms Authentication");
            }
        }
        public static void Upload(HttpServerUtility server, string virtualFolder, HttpPostedFile file, string filename)
        {
            string folder = server.MapPath(virtualFolder);
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            file.SaveAs(folder + filename);
        }
        /// <summary>
        /// Relative folder for file upload.E.g:"user1/2008/8/"
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string UploadRelativeFolder(string username)
        {
            var folder = string.Format("{0}/{1}/{2}/", username, DateTime.Now.Year, DateTime.Now.Month);
            return folder;
        }
        /// <summary>
        /// Relative full folder for file upload
        /// </summary>
        /// <returns></returns>
        public static string UploadRelativeFullFolder(string username)
        {
            var folder = string.Format("{0}{1}/{2}", Utils.RelativeWebRoot, "App_Data/files", UploadRelativeFolder(username));
            return folder;
        }
        #endregion

        /// <summary>
        /// compilation debug mode in web.config
        /// </summary>
        public static bool IsWebDebug
        {
            get
            {
                return HttpContext.Current.IsDebuggingEnabled;
            }
        }


        /// <summary>
        /// Writes ETag and Last-Modified headers and sets the conditional get headers.
        /// </summary>
        /// <param name="date">The date.</param>
        public static bool SetConditionalGetHeaders(DateTime date)
        {

            // SetLastModified() below will throw an error if the 'date' is a future date.
            if (date > DateTime.Now)
                date = DateTime.Now;

            HttpResponse response = HttpContext.Current.Response;
            HttpRequest request = HttpContext.Current.Request;

            string etag = String.Format("\"{0}\"", date.Ticks);
            string incomingEtag = request.Headers["If-None-Match"];

            DateTime incomingLastModifiedDate = DateTime.MinValue;
            DateTime.TryParse(request.Headers["If-Modified-Since"], out incomingLastModifiedDate);

            response.Cache.SetLastModified(date);
            response.Cache.SetCacheability(HttpCacheability.Public);
            response.Cache.SetETag(etag);

            if (String.Compare(incomingEtag, etag) == 0 || incomingLastModifiedDate == date)
            {
                response.Clear();
                response.StatusCode = (int)HttpStatusCode.NotModified;
                return true;
            }

            return false;
        }

        public static bool IsGoogleActive()
        {
            var retVal = false;
            var rawUrl = "http://www.google.com/";
            var request = WebRequest.Create(rawUrl);
            request.Timeout = 10000;
            try
            {
                var res = request.GetResponse();
                retVal = rawUrl.Equals(res.ResponseUri.ToString(), StringComparison.OrdinalIgnoreCase);
            }
            catch (Exception ex)
            {

            }
            return retVal;
        }
        public static bool IsGoogleJSAPIActive()
        {
            var retVal = false;
            var googleAPIUrl = AppSettingsHelper.Instance.GetString("google.jsAPIUrl", "http://www.google.com/jsapi");
            try
            {
                using (WebClient wc = new WebClient())
                {
                    var data = wc.DownloadString(googleAPIUrl);
                    retVal = !string.IsNullOrEmpty(data) && data.IndexOf("google.loader") > 0;
                }
            }
            catch (Exception ex)
            {

            }
            return retVal;
        }

        #region Is mobile device
        private const string MOBILE_REGEX_PATTERN = @"(nokia|sonyericsson|blackberry|samsung|sec\-|windows ce|motorola|mot\-|up.b|midp\-)";
        private static readonly Regex MOBILE_REGEX = new Regex(AppSettingsHelper.Instance.GetString("App.MobileDevices", MOBILE_REGEX_PATTERN), RegexOptions.IgnoreCase | RegexOptions.Compiled);

        /// <summary>
        /// Gets a value indicating whether the client is a mobile device.
        /// </summary>
        /// <value><c>true</c> if this instance is mobile; otherwise, <c>false</c>.</value>
        public static bool IsMobile
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    HttpRequest request = context.Request;
                    if (request.Browser.IsMobileDevice)
                        return true;

                    if (!string.IsNullOrEmpty(request.UserAgent) && MOBILE_REGEX.IsMatch(request.UserAgent))
                        return true;
                }

                return false;
            }
        }

        #endregion


        /// <summary>
        /// Resolves the region based on the browser language.
        /// </summary>
        public static RegionInfo BrowserRegionInfo()
        {
            string[] languages = HttpContext.Current.Request.UserLanguages;

            if (languages == null || languages.Length == 0)
                return new RegionInfo(CultureInfo.CurrentCulture.LCID);

            try
            {
                string language = languages[0].ToLowerInvariant().Trim();
                CultureInfo culture = CultureInfo.CreateSpecificCulture(language);
                return new RegionInfo(culture.LCID);
            }
            catch (ArgumentException)
            {
                try
                {
                    return new RegionInfo(CultureInfo.CurrentCulture.LCID);
                }
                catch (ArgumentException)
                {
                    // the googlebot sometimes gives a culture LCID of 127 which is invalid
                    // so assume US english if invalid LCID
                    return new RegionInfo(1033);
                }
            }
        }
    }
}
